﻿require 'open-uri'

class StockInfo < ActiveRecord::Base

  # sh_a, sz_a, cyb
  def self.load_from_internet(type)
    url = "http://vip.stock.finance.sina.com.cn/quotes_service/api/json_v2.php/Market_Center.getHQNodeData?page=1&num=4000&sort=symbol&asc=1&node=#{type}&symbol=&_s_r_a=page"
    
    # gsub处理不符合规范的json数据：key没有双引号包围
    str = open(url, 'r:gbk').read.gsub /([a-z]+):/, '"\1":'
    
    JSON.parse(str).each do |stock|
      stock.slice! "symbol", "code", "name", "trade", "per", "pb", "mktcap"
      stock["mktcap"] = stock["mktcap"].to_f * 10000
      stock["zone"] = type.to_s
      StockInfo.where(symbol: stock["symbol"]).first_or_initialize.update_attributes! stock
    end
    
    logger.info "finish load price #{type}"
  end
  
  def self.tick_sheets
    logger.info 'start tick_sheets'
    StockInfo.where(sheet_flag: nil).each do |info|
      StockSheet.where(symbol: info.symbol).first_or_initialize.update! tick_date: Date.today
      info.update! sheet_flag: 1
    end
    
    StockSheet.where(tick_date: Date.today).each_with_index do |sheet, idx|
      begin
        logger.info "runing tick_sheets #{idx}" if idx % 50 == 0
        sheet = StockSheet.load_sheets sheet.symbol
      rescue Exception => msg
        sheet.update! tick_date: '2010-01-01'
        logger.error msg
      else
        fndate = sheet.fndate.to_s["-12-31"].nil? ? sheet.fndate.to_date : sheet.fndate.to_date + 90
        day_diff = Date.today - fndate
        sheet.update! tick_date: (day_diff.to_i < 150 ? fndate + 150 : sheet.tick_date.to_date + 3)
      end
    end
    
    logger.info 'finish tick_sheets'
  end
  
end
